﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace WindowsFormsApplication2
{
    static class Multicast
    {
        private static string ipAdd = "239.5.42.47";
        private static int port = 50002;
        //always receive information
        public static void receive()
        {
            // Socket Creation
            Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
            // Bind to port 50002
            listenSocket.Bind(new IPEndPoint(IPAddress.Any, port));
            // Ask to receive from a specific Multicast IP Address
            listenSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(ipAdd)));
            Console.WriteLine("Receiver is runing");
            byte[] buffer = new byte[256];
            int recCount = 0;

            do
            {
                recCount = listenSocket.Receive(buffer);//every thing that receive is set on buffer (We must try to receive objects)
                Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, recCount));
            } while (true); 
        }

        public static void send(){
            // Socket Creation
            Socket sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            // Target to send the datas
            EndPoint multicastEndPoint = new IPEndPoint(IPAddress.Parse(ipAdd), port);
            string HelloString = "Enviando data";

            do
            {
                sendSocket.SendTo(Encoding.UTF8.GetBytes(HelloString), HelloString.Length, SocketFlags.None, multicastEndPoint);
            } while (true);
        }
    }
}
